const express = require("express");
const file = express.Router();
const multer = require('multer');

const fs = require('fs');
const path = require('path');
// file.use(express.static(path.join(__dirname, 'public')));


// 返回上传文件的路径
let imgUrl = '';
let imgUrlArray = [];
// 上传图片的链接
const headerConfigImg = multer.diskStorage({
    dest: 'public/file/img',
    filename: function (req, file, callback) {
        let nameId = new Date();
        let name = nameId.getTime();
        let type = file.originalname.split('.');
        type = type[type.length - 1];
        let imgName = name + '.' + type;
        imgUrl = "http://localhost:9000/file/img/" + imgName;
        imgUrlArray.push(imgUrl);
        callback(null, imgName);
    }
});
const uploadImg = multer({
    storage: headerConfigImg
});

file.post('/uploadImg', function (req, res) {
    if(req.files == undefined) {
		res.send("您还未选择要上传的图片");
	}else{
		console.log("length---------------")
		console.log(req.files.length)
		console.log("length---------------")
		for(var i=0; i<req.files.length; i++){
			var file_path = req.files[i].path;
			var des_file = __dirname + '/public/images/' + req.files[i].originalname;
			fs.renameSync(file_path, des_file);
		}
		res.send("上传图片成功")
	}
    // uploadImg(req, res, function (err, doc) {
    //     console.log(err);
    //     console.log(doc);

    //     if (err) {
    //         res.send({
    //             status: 500,
    //         });
    //         return
    //     }
    //     console.log('上传正常');
    //     console.log(doc);
    //     res.send({
    //         status: 200,
    //         link: imgUrl,
    //     });
    // });
});
module.exports = file;